﻿using System;
using System.ServiceModel.Channels;

namespace YawetagLib.ServiceModel
{
    public abstract class ServiceProxy<TService> : IDisposable
    {
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                if (disposing)
                {
                    ManagedResourceCleanup();
                }
                UnmanagedResourceCleanup();
                IsDisposed = true;
            }
        }

        protected virtual void ManagedResourceCleanup()
        {
            ChannelFactory.Close();
        }

        protected virtual void UnmanagedResourceCleanup()
        {
        }

        ~ServiceProxy()
        {
            Dispose(false);
        }

        protected IChannelFactory<TService> ChannelFactory { get; set; }
        protected TService Service { get; set; }

        private bool IsDisposed { get; set; }
    }
}
